<template>
  <div class="media-player">
    <el-card class="media-card">
      <template #header>
        <div class="card-header">
          <span>{{ mediaData.title || '媒体播放器' }}</span>
        </div>
      </template>

      <div class="media-content">
        <!-- Audio/Video Player -->
        <div class="player-container">
          <audio
            v-if="mediaData.audio_file"
            ref="mediaPlayer"
            :src="mediaData.audio_file"
            @timeupdate="onTimeUpdate"
            @play="onPlay"
            @pause="onPause"
            @ended="onEnded"
            controls
            class="media-element"
          ></audio>

          <video
            v-else-if="mediaData.video_file"
            ref="mediaPlayer"
            :src="mediaData.video_file"
            @timeupdate="onTimeUpdate"
            @play="onPlay"
            @pause="onPause"
            @ended="onEnded"
            controls
            class="media-element"
          ></video>

          <div v-else class="no-media">未提供媒体文件</div>
        </div>

        <!-- Subtitle Display -->
        <subtitle-display
          :subtitle="currentSubtitle"
          :current-time="currentTime"
          @subtitle-click="handleSubtitleClick"
        />

        <!-- Word Definition Panel -->
        <word-details :word="selectedWord" />

        <word-pronunciation 
          :word="selectedWord" 
          :is-playing="isPlaying"
          @play="playPronunciation"
          @stop="stopPronunciation"
        />

        <div style="margin-top: 15px;">
          <el-button 
            size="small" 
            :type="selectedWord.ok === 'YES' ? 'warning' : 'info'"
            @click="toggleWordStatus"
          >
            {{ selectedWord.ok === 'YES' ? '标记为未掌握' : '标记为已掌握' }}
          </el-button>
          
          <el-tag 
            v-if="selectedWord.ielst === 'YES'" 
            type="success" 
            size="small"
            effect="dark"
            style="margin-left: 10px;"
          >
            雅思词汇
          </el-tag>
        </div>

        <!-- Media Controls -->
        <div class="media-controls">
          <el-button-group>
            <el-button @click="rewind(10)">
              <el-icon><RefreshLeft /></el-icon> -10s
            </el-button>
            <el-button @click="togglePlay">
              <el-icon><component :is="isPlaying ? 'VideoPause' : 'VideoPlay'" /></el-icon>
              {{ isPlaying ? '暂停' : '播放' }}
            </el-button>
            <el-button @click="fastForward(10)">
              <el-icon><RefreshRight /></el-icon> +10s
            </el-button>
          </el-button-group>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElCard, ElTable, ElTableColumn, ElButton, ElIcon, ElMessage } from 'element-plus';
import { VideoPlay, VideoPause, Volume, Refresh } from '@element-plus/icons-vue';
import SubtitleDisplay from './SubtitleDisplay.vue';
import WordDetails from './WordDetails.vue';
import WordPronunciation from './WordPronunciation.vue';
import { updateWordStatus } from '../utils';

export default {
  name: 'MediaPlayer',
  components: {
    ElCard,
    ElTable,
    ElTableColumn,
    ElButton,
    ElIcon,
    ElMessage,
    VideoPlay,
    VideoPause,
    Volume,
    Refresh,
    SubtitleDisplay,
    WordDetails,
    WordPronunciation
  },
  props: {
    mediaData: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      currentTime: 0,
      isPlaying: false,
      currentSubtitle: null,
      selectedWord: null,
      activeCollapse: ['definition'],
    };
  },
  mounted() {
    // Try to load subtitles if available
    if (this.mediaData.subtitle_file) {
      this.loadSubtitles();
    }
  },
  methods: {
    onTimeUpdate(event) {
      this.currentTime = event.target.currentTime;
      this.updateSubtitle();
    },

    onPlay() {
      this.isPlaying = true;
    },

    onPause() {
      this.isPlaying = false;
    },

    onEnded() {
      this.isPlaying = false;
    },

    togglePlay() {
      const player = this.$refs.mediaPlayer;
      if (player) {
        if (this.isPlaying) {
          player.pause();
        } else {
          player.play();
        }
      }
    },

    rewind(seconds) {
      const player = this.$refs.mediaPlayer;
      if (player) {
        player.currentTime = Math.max(0, player.currentTime - seconds);
      }
    },

    fastForward(seconds) {
      const player = this.$refs.mediaPlayer;
      if (player) {
        player.currentTime = player.currentTime + seconds;
      }
    },

    async updateSubtitle() {
      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.getSubtitle) {
          // In a real implementation, this would call the media service to get the subtitle at current time
          // For now, we'll keep the simulation but add a note that this needs real implementation
          console.log('Need to implement real subtitle fetching via electronAPI');
        }

        // Keep the simulation for now until we have the real implementation
        if (this.mediaData.subtitle_file) {
          // Simulate getting subtitle based on time
          // In real implementation, this would use the MediaService
          this.currentSubtitle = {
            text: `示例字幕文本 - 时间: ${this.currentTime.toFixed(2)}s`,
            start: this.currentTime,
            end: this.currentTime + 3,
          };
        }
      } catch (err) {
        console.error('Error updating subtitle:', err);
      }
    },

    async loadSubtitles() {
      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.loadSubtitles) {
          // In a real implementation, this would load and parse the actual subtitle file
          console.log(`Loading subtitles from: ${this.mediaData.subtitle_file}`);
          // For now, we'll just log that this needs real implementation
          console.log('Need to implement real subtitle loading via electronAPI');
        } else {
          console.log(`Loading subtitles from: ${this.mediaData.subtitle_file}`);
        }
      } catch (err) {
        console.error('Error loading subtitles:', err);
      }
    },

    handleSubtitleClick(data) {
      // Handle click on subtitle display
      console.log('Subtitle clicked:', data);
      this.$emit('subtitle-interact', data);
    },

    async toggleWordStatus() {
      if (this.selectedWord) {
        await updateWordStatus(this.selectedWord, {
          success: (msg) => this.$message.success(msg),
          error: (msg) => this.$message.error(msg)
        });
      }
    },

    async playPronunciation() {
      if (this.selectedWord) {
        try {
          // Check if electronAPI is available
          if (typeof window.electronAPI !== 'undefined' && window.electronAPI.playPronunciation) {
            // Get the pronunciation path from the word data
            const audioPath = this.selectedWord.uk_speech || this.selectedWord.us_speech;

            if (audioPath) {
              const response = await window.electronAPI.playPronunciation(audioPath);

              if (response.success) {
                this.$message.success(`正在播放发音: ${this.selectedWord.word}`);
              } else {
                throw new Error(response.error || 'Failed to play pronunciation');
              }
            } else {
              this.$message.warning('该单词没有发音资源');
            }
          } else {
            console.warn('Electron API not available, running in browser development mode');
            this.$message.success(`播放发音: ${this.selectedWord.word}`);
          }
        } catch (err) {
          console.error('Error playing pronunciation:', err);
          this.$message.error('播放发音失败: ' + err.message);
        }
      }
    },
  },
};
</script>

<style scoped>
.media-player {
  max-width: 800px;
  margin: 0 auto;
}

.media-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

.media-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.player-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.media-element {
  width: 100%;
  outline: none;
}

.no-media {
  color: #999;
  font-style: italic;
}

.word-panel {
  margin-top: 20px;
}

.word-translation,
.word-phonetic {
  margin: 10px 0;
}

.media-controls {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
